#!/bin/bash

TPCH_TABLES=(customer lineitem nation orders partsupp part region supplier)

LOAD_DB=pgsql
LOAD_TOOL=psql
DB_NAME=postgres
DB_PORT=5432
COPY_DLM=\|

if [ $# -ge 2 ]; then
  DB_NAME=$2
fi

if [ $# -ge 3 ]; then
  if [ "$3" = "gauss" ]; then
    LOAD_DB=gauss
  fi
fi

if [ "$LOAD_DB" = "gauss" ]; then
  LOAD_TOOL=gsql

  if test "${GAUSSHOME+set}" = set; then
    BIN_PATH=$GAUSSHOME/bin
  else
    if [ -e ./$LOAD_TOOL ]; then
      BIN_PATH=.
    fi
  fi
else
  if test "${PGHOME+set}" = set; then
    BIN_PATH=$PGHOME/bin
  else
    if [ -e ./$LOAD_TOOL ]; then
      BIN_PATH=.
    fi
  fi
fi

if test "${BIN_PATH+set}" = set; then
  if [ ! -e $BIN_PATH/$LOAD_TOOL ]; then
    echo "could not find" $LOAD_TOOL
    exit
  fi
  LOAD_TOOL=$BIN_PATH/$LOAD_TOOL
fi

$LOAD_TOOL -c "SELECT 1" -p $DB_PORT $DB_NAME > /dev/null
if [ $? -ne 0 ]; then
  echo error: could not connect to database server.
  exit
fi

TIME_START=`date +%s`

for i in `ls $1/*.tbl`;
do

fname=$(basename "$i")
tname="${fname%.*}"

if [[ ! "${TPCH_TABLES[@]}" =~ "${tname}" ]]; then
  echo "WARNING: ignore \"$i\""
  continue
fi

echo "LOADING $tname TO database \"$DB_NAME\" ...";

LOAD_START=`date +%s`
$LOAD_TOOL -c "COPY $tname FROM '$i' DELIMITER '$COPY_DLM'" -p $DB_PORT $DB_NAME
LOAD_END=`date +%s`

LOAD_TIME=$[ $LOAD_END - $LOAD_START ]
if [ $LOAD_TIME -gt 0 ]; then
  echo "Load time: " $LOAD_TIME "second(s)"
fi

done;

TIME_END=`date +%s`
TOTAL_TIME=$[ $TIME_END - $TIME_START ]

if [ $TOTAL_TIME -gt 0 ]; then
  echo "Total: " $TOTAL_TIME "second(s)"
fi
